package com.xxxx.game;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;

/*
 * As app runs, the vm heap memory will grow. Every vm has a limit heap size which is related to the device and the version of Android.
 * if the heap size of VM exceeds to its max size, app will crash. 
 * */

public class Memory {
	private static final float KB = 1024.0f;
	private static final float RESERVE_SIZE = 6*1024;
	//return size of an object in KB
	public static final float MemoryForObject(Object obj) throws IOException
	{
		if(obj != null)
			{
				ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
				ObjectOutputStream objOutputStream = new ObjectOutputStream(byteArrayStream);
				objOutputStream.writeObject(obj);
				objOutputStream.flush();
				objOutputStream.close();
				
				float size = byteArrayStream.toByteArray().length / KB;
				byteArrayStream.close();
				return size;
			}
		return -1;	

	}
	
	//max size of heap for current app
	public static final float MaxHeapSize()
	{
		Runtime runtime = Runtime.getRuntime();
		return runtime.maxMemory() / KB;
	}
	
	//return if the systerm memory is low
	public static boolean IsMemoryLow(Context context)
	{
		ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo outInfo = new MemoryInfo();
		manager.getMemoryInfo(outInfo);
		return outInfo.lowMemory;
	}
	
	//Current heap size for current app
	public static float CurrentHeapSize(Context context)
	{
		Runtime runtime =  Runtime.getRuntime();
		return runtime.totalMemory() / KB;
	}
	
	//memory still available for current app
	public static float AvailableMemorySize(Context context)
	{
		Runtime runtime = Runtime.getRuntime();
		return (runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory())) / KB - RESERVE_SIZE;
	}
	

}
